package com.leboncoin.batch;

import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;


import com.leboncoin.bean.SearchItemBean;
import com.leboncoin.bean.SubscriptionBean;
import com.leboncoin.mail.MailManager;
import com.leboncoin.xml.ConfigManager;
import java.util.logging.Level;

public class DaySearch {

    protected static final Logger logger = Logger.getLogger(DaySearch.class.getName());

    public static void main(String args[]) {
        try {
            DaySearch daySearch = new DaySearch();
            String confFile = "conf/daySearch.xml";
            if (args.length > 0) confFile = args[0];
            ConfigManager.getInstance(confFile);
            daySearch.testSearch();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "", e);
        }
    }

    public void testSearch() throws Exception {

        for (SubscriptionBean subscriptionBean : ConfigManager.getInstance(null).getSubscriptions()) {

            CommonSearch commonSearch = CommonSearch.getInstance();
            commonSearch.searchFromSubscription(true, subscriptionBean);
            MailManager.sendMail(subscriptionBean);

         
            EntityManagerFactory emf = null;
            EntityManager em = null;
            EntityTransaction transac = null;
            try {
                emf = Persistence.createEntityManagerFactory("leboncoin");
                em = emf.createEntityManager();
                transac = em.getTransaction();
                transac.begin();

                for (SearchItemBean searchItemBean : subscriptionBean.getSearchItems()) {
                    // for persistence, empty primary key is a problem
                    if ("".equals(searchItemBean.getSearchText())) {
                        searchItemBean.setSearchText("empty text");
                    }
                    em.merge(searchItemBean);
                }

                transac.commit();
            } catch (Exception e) {
                logger.log(Level.SEVERE, "Persistence failure", e);
                if (transac != null && transac.isActive()) {
                    transac.rollback();
                }
            } finally {
                if (em != null) {
                    em.close();
                }
                if (emf != null) {
                    emf.close();
                }
            }
        }
        
    }

}
